package com.ekuaitu.kuaitu.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.AwardBean;
import com.ekuaitu.kuaitu.bean.MyCardBean;
import com.ekuaitu.kuaitu.bean.PraizeMarqueeBean;
import com.ekuaitu.kuaitu.bean.ShakeResultBean;
import com.ekuaitu.kuaitu.utils.BitmapUtil;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.ekuaitu.kuaitu.widget.GifView;
import com.ekuaitu.kuaitu.widget.MarqueeView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jieyaozu on 2017/5/31.
 * 摇一摇抽奖页面
 */

public class ShakeActivity extends BaseActivity implements View.OnClickListener {
    private SensorManager sensorManager;
    private Vibrator vibrator;
    private static final String TAG = "TestSensorActivity";
    private static final int SENSOR_SHAKE = 10;

    private ImageView ivBack;
    private RelativeLayout layoutInit, layoutSuccess, layoutFailed;
    private ImageView ivSuccessClose, ivFailedClose;
    private TextView tvButtonTake, tvButtonContinue, tvFailedButtonContinue;
    private TextView tvFailedMessage, tvSuccessMessage, tvResultMessage;
    private TextView tvShakeResultNoChange;

    private String latitude, longitude, areaCode, address;
    private String shakeId;
    private TextView tvShakeDetail;

    private MarqueeView marqueeView;

    private GifView shakingGold;
    private ImageView ivShakeHand;
    private ImageView ivShakeLightBg;
    //插入音频
    private SoundPool soundPool;
    private int soundId, streamId;
    float volumnRatio;
    float audioMaxVolumn;
    float volumnCurrent;
    private boolean isplaying = false;
    private boolean isReceivePrize = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_shake;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void initView() {
        //初始化音频播放
        soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        soundId = soundPool.load(this, R.raw.shake_sound_male, 1);
        AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        volumnCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        volumnRatio = volumnCurrent / audioMaxVolumn;

        StatusBarUtil.setColor(this, getResources().getColor(R.color.shake_bg), 0, false);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        ivBack = (ImageView) findViewById(R.id.return_shake);
        layoutInit = (RelativeLayout) findViewById(R.id.shake_init_layout);
        layoutSuccess = (RelativeLayout) findViewById(R.id.shake_success_layout);
        layoutFailed = (RelativeLayout) findViewById(R.id.shake_failed_layout);
        ivSuccessClose = (ImageView) findViewById(R.id.shake_success_close);
        ivFailedClose = (ImageView) findViewById(R.id.shake_failed_close);
        tvButtonTake = (TextView) findViewById(R.id.shake_button_take);
        tvButtonContinue = (TextView) findViewById(R.id.shake_button_continue);
        tvFailedButtonContinue = (TextView) findViewById(R.id.shake_failed_button_continue);
        tvFailedMessage = (TextView) findViewById(R.id.shake_failed_message);
        tvSuccessMessage = (TextView) findViewById(R.id.shake_success_message);
        tvResultMessage = (TextView) findViewById(R.id.shake_result_message);
        tvShakeResultNoChange = (TextView) findViewById(R.id.shake_result_nochance);
        tvShakeDetail = (TextView) findViewById(R.id.shake_detail);
        shakingGold = (GifView) findViewById(R.id.shakeing_gold_bg);
        ivShakeHand = (ImageView) findViewById(R.id.shake_hand_image);
        ivShakeLightBg = (ImageView) findViewById(R.id.shake_light_bg);
        marqueeView = (MarqueeView) findViewById(R.id.scroll_textView);

        ivBack.setOnClickListener(this);
        ivSuccessClose.setOnClickListener(this);
        ivFailedClose.setOnClickListener(this);
        tvButtonTake.setOnClickListener(this);
        tvButtonContinue.setOnClickListener(this);
        tvShakeDetail.setOnClickListener(this);
        tvFailedButtonContinue.setOnClickListener(this);

        latitude = getIntent().getStringExtra(IntentKey.INTENT_LATITUDE);
        longitude = getIntent().getStringExtra(IntentKey.INTENT_LONGITUDE);
        areaCode = getIntent().getStringExtra(IntentKey.INTENT_AREACODE);
        address = "";//getIntent().getStringExtra(IntentKey.INTENT_ADDRESS);
        layoutInit.postDelayed(new Runnable() {
            @Override
            public void run() {
                shakingGold.setMovieResource(R.raw.shaking_bg);
                stopAnimationShakingbg();
            }
        }, 1000);
        getMarqueeData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sensorManager != null) {// 注册监听器
            sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
            // 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
        }
        if (isReceivePrize) {
            isReceivePrize = false;
            layoutSuccess.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (sensorManager != null) {// 取消监听器
            sensorManager.unregisterListener(sensorEventListener);
        }
    }

    /**
     * 开奖的跑马灯数据
     */
    private void getMarqueeData() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getPraizeMarqueeData(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<PraizeMarqueeBean>() {
            @Override
            public void onResponse(Call<PraizeMarqueeBean> call, Response<PraizeMarqueeBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    PraizeMarqueeBean.AttachmentBean attachmentBean = response.body().getAttachment();
                    if (attachmentBean != null) {
                        List<PraizeMarqueeBean.DataLottery> lotteryList = attachmentBean.getDataLotteryList();
                        List strings = new ArrayList();
                        for (int i = 0; i < lotteryList.size(); i++) {
                            PraizeMarqueeBean.DataLottery dataLottery = lotteryList.get(i);
                            String stringdata = dataLottery.getPhone() + "," + "中奖" + dataLottery.getMoney() + "元," + "第" + dataLottery.getIssue() + "期";
                            i++;
                            if (i < lotteryList.size()) {
                                dataLottery = lotteryList.get(i);
                                stringdata += "\n" + dataLottery.getPhone() + "," + "中奖" + dataLottery.getMoney() + "元," + "第" + dataLottery.getIssue() + "期";
                            }
                            strings.add(stringdata);
                        }
                        marqueeView.startWithList(strings, null);
                    }
                }
            }

            @Override
            public void onFailure(Call<PraizeMarqueeBean> call, Throwable t) {

            }
        });
    }

    /**
     * 获得摇一摇后的结果
     */
    private void getShakePrize() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getShakePrize(MyApplication.getInstance().getRequestFieldMap(), latitude, longitude, address).enqueue(new Callback<ShakeResultBean>() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onResponse(Call<ShakeResultBean> call, Response<ShakeResultBean> response) {
                closeBaseProgressDialog();
                if (response.isSuccessful() && response.body() != null) {
                    ShakeResultBean.AttachmentBean attachmentBean = response.body().getAttachment();
                    if (attachmentBean != null && "0".equals(attachmentBean.getIsShowShake())) {
                        ToastCompat.makeText(ShakeActivity.this, "活动已经结束!", Toast.LENGTH_SHORT).show();
                        Constants.SHAKE_ACTIVITY_IS_END = true;
                        return;
                    }
                    if (response.body().getStatus() == 200) {//有奖
                        tvShakeResultNoChange.setVisibility(View.GONE);
                        String isHaveAwards = "0";
                        if (attachmentBean != null) {
                            isHaveAwards = attachmentBean.getIsHaveAwards();
                            tvSuccessMessage.setText("获得" + isHaveAwards + "张");
                            tvResultMessage.setText(response.body().getMessage().substring(4).trim());
                        }
                        if (Integer.parseInt(isHaveAwards) > 0) {//有奖
                            layoutSuccess.setBackground(getBlurBackground());
                            layoutSuccess.setVisibility(View.VISIBLE);
                        } else {//无奖
                            layoutFailed.setBackground(getBlurBackground());
                            layoutFailed.setVisibility(View.VISIBLE);
                            tvFailedMessage.setText(response.body().getMessage());
                        }
                        shakeId = attachmentBean != null ? attachmentBean.getShakeId() : "";
                    } else if (response.body().getStatus() == 401) {//机会用完
                        tvShakeResultNoChange.setVisibility(View.VISIBLE);
                        tvShakeResultNoChange.setText(response.body().getMessage());
                    }
                }
            }

            @Override
            public void onFailure(Call<ShakeResultBean> call, Throwable t) {
                closeBaseProgressDialog();
            }
        });
    }

    /**
     * 领奖
     */
    private void receivePrize() {
        showBaseProgressDialog("领取中...");
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).receivePrize(MyApplication.getInstance().getRequestFieldMap(), shakeId).enqueue(new Callback<AwardBean>() {
            @Override
            public void onResponse(Call<AwardBean> call, Response<AwardBean> response) {
                closeBaseProgressDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        AwardBean.Attachment attachment = response.body().getAttachment();
                        String type = attachment.getType();//1:商户券，2：优惠券
                        if ("1".equals(type)) {
                            AwardBean.Attachment.CardCouponModel cardCouponModel = attachment.getCardCouponModel();
                            MyCardBean.AttachmentBean.CardCouponModelsBean cardCouponModelsBean = castBean(cardCouponModel);
                            Intent intent = new Intent(ShakeActivity.this, MyCardDetailActivity.class);
                            intent.putExtra("cardDetail", cardCouponModelsBean);
                            startActivity(intent);
                        } else if ("2".equals(type)) {
                            startActivity(new Intent(ShakeActivity.this, MyCouponActivity.class));
                        } else if ("3".equals(type)) {
                            Intent intent = new Intent(ShakeActivity.this, WebViewActivity.class);
                            intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "双色球");
                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, attachment.getCardCouponModel().getLotteryUrl());
                            startActivity(intent);
                        }
                        isReceivePrize = true;
                    }
                    ToastCompat.makeText(ShakeActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AwardBean> call, Throwable t) {
                closeBaseProgressDialog();
            }
        });
    }

    private MyCardBean.AttachmentBean.CardCouponModelsBean castBean(AwardBean.Attachment.CardCouponModel cardCouponModel) {
        MyCardBean.AttachmentBean.CardCouponModelsBean cardCouponModelsBean = new MyCardBean.AttachmentBean.CardCouponModelsBean();
        cardCouponModelsBean.setBusinessName(cardCouponModel.getBusinessName());
        cardCouponModelsBean.setDenomination(cardCouponModel.getDenomination());
        cardCouponModelsBean.setStartDate(cardCouponModel.getStartDate());
        cardCouponModelsBean.setEndDate(cardCouponModel.getEndDate());
        cardCouponModelsBean.setCode(cardCouponModel.getCode());
        cardCouponModelsBean.setBusinessAddress(cardCouponModel.getBusinessAddress());
        cardCouponModelsBean.setContent(cardCouponModel.getContent());
        return cardCouponModelsBean;
    }

    /**
     * 重力感应监听
     */
    private SensorEventListener sensorEventListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            // 传感器信息改变时执行该方法
            float[] values = event.values;
            float x = values[0]; // x轴方向的重力加速度，向右为正
            float y = values[1]; // y轴方向的重力加速度，向前为正
            float z = values[2]; // z轴方向的重力加速度，向上为正
            Log.i(TAG, "x轴方向的重力加速度" + x + "；y轴方向的重力加速度" + y + "；z轴方向的重力加速度" + z);
            // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
            int medumValue = 15;// 如果不敏感请自行调低该数值,低于10的话就不行了,因为z轴上的加速度本身就已经达到10了
            if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {
                if (layoutSuccess.getVisibility() != View.VISIBLE && layoutFailed.getVisibility() != View.VISIBLE) {
                    vibrator.vibrate(200);
                    playShakeSound();
                    Message msg = new Message();
                    msg.what = SENSOR_SHAKE;
                    handler.removeMessages(SENSOR_SHAKE);
                    handler.sendMessageDelayed(msg, 1000);
                    startAnimationShakingbg();
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    private void startAnimationShakingbg() {
        closeBaseProgressDialog();
        shakingGold.setVisibility(View.VISIBLE);
        Animation operatingAnim = AnimationUtils.loadAnimation(ShakeActivity.this, R.anim.shake);
        AccelerateInterpolator interpolator = new AccelerateInterpolator();
        operatingAnim.setInterpolator(interpolator);
        ivShakeHand.startAnimation(operatingAnim);

        //背景光 （暂时去掉）
/*        Animation scaleAnimation = AnimationUtils.loadAnimation(ShakeActivity.this, R.anim.shake_scale_anim);
        ivShakeLightBg.startAnimation(scaleAnimation);
        ivShakeLightBg.setVisibility(View.VISIBLE);*/
    }

    private void stopAnimationShakingbg() {
        shakingGold.setVisibility(View.GONE);
        ivShakeHand.clearAnimation();
        ivShakeLightBg.clearAnimation();
        ivShakeLightBg.setVisibility(View.INVISIBLE);
    }

    /**
     * 动作执行
     */
    Handler handler = new Handler() {

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SENSOR_SHAKE:
                    pauseShakeSound();
                    stopAnimationShakingbg();
                    showBaseProgressDialog("摇奖中...");
                    layoutInit.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            getShakePrize();
                        }
                    }, 500);
                    break;
            }
        }

    };

    /**
     * 获得高斯模糊的背景
     *
     * @return
     */
    private BitmapDrawable getBlurBackground() {
        // 获取壁纸管理器
        // 将Drawable,转成Bitmap 
        View view = getWindow().getDecorView().getRootView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        return new BitmapDrawable(getResources(), BitmapUtil.blur(ShakeActivity.this, bmp));
    }

    /**
     * 播放音频
     */
    private void playShakeSound() {
        if (!isplaying) {
            isplaying = true;
            streamId = soundPool.play(soundId, audioMaxVolumn, audioMaxVolumn, 1, -1, 1.0f);
        }
    }

    /**
     * 暂停播放
     */
    private void pauseShakeSound() {
        isplaying = false;
        soundPool.stop(streamId);
        soundId = soundPool.load(this, R.raw.shake_sound_male, 1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.return_shake:
                finish();
                break;
            case R.id.shake_success_close:
                layoutSuccess.setVisibility(View.GONE);
                break;
            case R.id.shake_failed_close:
                layoutFailed.setVisibility(View.GONE);
                break;
            case R.id.shake_button_take:
                receivePrize();
                break;
            case R.id.shake_button_continue:
                layoutSuccess.setVisibility(View.GONE);
                break;
            case R.id.shake_failed_button_continue:
                layoutFailed.setVisibility(View.GONE);
                break;
            case R.id.shake_detail:
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "活动详情");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.SHAKE_DETAIL);
                startActivity(intent);
                break;
        }
    }
}
